/**
 * Created by Administrator on 2017/8/3.
 */
var LOGIN_URL = "http://39.108.226.96/HSZWeb/GetLoginData";


$(function () {
    var BODY_BGS = [
        "http://img.tuku.com/upload/attach/2013/07/98031-9wo1TE2.jpg",
        "http://image5.tuku.cn/wallpaper/Landscape%20Wallpapers/8294_2560x1600.jpg",
        "http://pic1.win4000.com/wallpaper/6/512ab98606b0c.jpg",
        "http://i5.download.fd.pchome.net/t_960x600/g1/M00/0C/1C/ooYBAFR7xWqIYSfwAAUXrdryK4cAACH7QFkTDwABRfF023.jpg",
        "http://image5.tuku.cn/wallpaper/Landscape%20Wallpapers/8294_2560x1600.jpg",
    ];
    var randomNum = Math.ceil(Math.random() * BODY_BGS.length) - 1;
    $(".bg").css("background-image", "url(" + BODY_BGS[randomNum] + ")");


    $('.login_wrap > .login_body > input').on('keydown', function (e) {
        var key = e.which;
        if (key == 13) {
            //
            checked(success, showError);
        }
    })

    $('.login_wrap > .login_body>button').on('click', function () {
        checked(success, showError);
    });

    function success() {
        $.ajax(
            {
                url: LOGIN_URL,
                type: "post",
                data: {
                    username: $('.login_wrap > .login_body > input').eq(0).val(),
                    password: $('.login_wrap > .login_body > input').eq(1).val()
                },
                success: function (res) {
                    if (res.code == 200) {
                        // 说明登录成功
                        var userInfo = {
                            username: $('.login_wrap > .login_body > input').eq(0).val(),
                            token: res.data.token
                        }
                        location.href = "pages/main.html?userInfo=" + encodeURI(JSON.stringify(userInfo));
                    } else {
                        showError(res.data);
                    }
                },
                error: function () {
                    showError("请求错误")
                }
            }
        )
    }


    function checked(success, error) {
        var username = $('.login_wrap > .login_body > input').eq(0).val();
        var pass = $('.login_wrap > .login_body > input').eq(1).val();
        username = username.replace(" ", "");
        pass = username.replace(" ", "");
        if (username && pass) {
            hideError();
            success();
        } else {
            error('用户名/密码不能为空');
        }
    }

    function showError(msg) {
        $(".login_info").text(msg).slideDown();
    }

    function hideError() {
        $(".login_info").slideUp();
    }
});